package com.ctshk.rpc.order.custom.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.utils.CharUtil;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.custom.dto.trip.TripScheduleAdvancedDTO;
import com.ctshk.rpc.custom.req.trip.CustomizedTripScheduleDTO;
import com.ctshk.rpc.custom.service.ICustomizedTripScheduleService;
import com.ctshk.rpc.finance.req.stamptax.StampTaxRefundAddReq;
import com.ctshk.rpc.finance.service.IFinanceStampTaxRefundService;
import com.ctshk.rpc.order.custom.code.CollectionRefundWayIdCode;
import com.ctshk.rpc.order.custom.code.CollectionTypeIdCode;
import com.ctshk.rpc.order.custom.code.DataSourceCode;
import com.ctshk.rpc.order.custom.code.SeriesOrderTouristOtherFeeFeeTypeCode;
import com.ctshk.rpc.order.custom.constant.Constants;
import com.ctshk.rpc.order.custom.dto.order.*;
import com.ctshk.rpc.order.custom.dto.tourist.TouristReceiptInfoDTO;
import com.ctshk.rpc.order.custom.entity.*;
import com.ctshk.rpc.order.custom.mapper.*;
import com.ctshk.rpc.order.custom.req.order.*;
import com.ctshk.rpc.order.custom.service.ICustomizedOrderCollectionService;
import com.ctshk.rpc.order.custom.service.ICustomizedOrderReceiptService;
import com.ctshk.rpc.order.custom.service.INumberService;
import com.ctshk.rpc.order.custom.util.OrderUtil;
import com.ctshk.rpc.order.custom.vo.SalesReceiptJson;
import com.ctshk.rpc.stamp.dto.LevyDTO;
import com.ctshk.rpc.stamp.req.LevyRequest;
import com.ctshk.rpc.stamp.service.ILevyService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.enums.ISCode;
import com.ctshk.rpc.system.service.IMainDataCurrencyService;
import com.ctshk.rpc.system.service.ISysDepartmentService;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.*;

/**
 * <p>
 * 订单收据 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-02-22
 */
@DubboService
public class CustomizedOrderReceiptServiceImpl extends ServiceImpl<CustomizedOrderReceiptMapper, CustomizedOrderReceipt> implements ICustomizedOrderReceiptService {

    @Autowired
    private CustomizedOrderReceiptMapper orderReceiptMapper;
    @Autowired
    private CustomizedOrderCollectionMapper orderCollectionMapper;
    @Autowired
    private CustomizedOrderTouristInfoMapper orderTouristInfoMapper;
    @Autowired
    private CustomizedOrderTouristOtherFeeMapper orderTouristOtherFeeMapper;
    @Autowired
    private CustomizedOrderTouristFeeAdjustMapper orderTouristFeeAdjustMapper;
    @Autowired
    private CustomizedOrderReceiptDetailsMapper orderReceiptDetailsMapper;
    @Autowired
    private CustomizedOrderReceiptTouristMapper orderReceiptTouristMapper;
    @Autowired
    private CustomizedOrderAmountStatisticsMapper orderAmountStatisticsMapper;
    @Autowired
    private CustomizedOrderMapper orderMapper;
    @Autowired
    private CustomizedOrderInsurancePriceTouristMapper orderInsurancePriceTouristMapper;
    @Autowired
    private CustomizedOrderReceiptInsuranceMapper orderReceiptInsuranceMapper;
    @Autowired
    private CustomizedOrderInsuranceMapper orderInsuranceMapper;

    @DubboReference
    private ICustomizedTripScheduleService tripScheduleService;
    @DubboReference
    private ISysUserService userService;
    @DubboReference
    private ISysDepartmentService departmentService;
    @DubboReference
    private INumberService numberService;
    @DubboReference
    private ICustomizedOrderCollectionService orderCollectionService;
    //印花税
    @DubboReference
    private ILevyService levyService;
    @DubboReference
    private IMainDataCurrencyService iMainDataCurrencyService;
    @DubboReference
    private IFinanceStampTaxRefundService financeStampTaxRefundService;
    @DubboReference
    private ISysUserService sysUserService;



    /**
     * 收據列表
     *
     * @param req
     * @return
     */
    @Override
    public CustomOrderReceiptListCountDTO list(OrderReceiptListReq req) {
        QueryWrapper<CustomizedOrderAmountStatistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomizedOrderAmountStatistics::getOrderId, req.getOrderId());
        CustomizedOrderAmountStatistics statistics = orderAmountStatisticsMapper.selectOne(queryWrapper);
        CustomOrderReceiptListCountDTO dto = new CustomOrderReceiptListCountDTO();
        dto.setReceiptedAmount(statistics.getReceiptedAmount());
        dto.setNotReceivedAmount(statistics.getTotalPaidIn().subtract(statistics.getReceiptedAmount()));

        IPage<OrderReceiptListReq> page = new Page<>(req.getPageNo(), req.getPageSize());
        IPage<CustomOrderReceiptListDTO> pageResult = orderReceiptMapper.selectListBySelective(page, req);
        pageResult.getRecords().forEach(receipt -> {
            if (Objects.equals(receipt.getReceiptType(),1)){
                //销售收据
                QueryWrapper<CustomizedOrderReceiptDetails> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("receipt_id",receipt.getId());
                CustomizedOrderReceiptDetails details = orderReceiptDetailsMapper.selectOne(queryWrapper1);
                if (details != null && StringUtils.isNotBlank(details.getReceipJson())){
                    SalesReceiptJson salesReceiptJson = JSON.parseObject(details.getReceipJson(), SalesReceiptJson.class);
                    List<ReceiptTouristInfoDTO> touristInfoDTOList = salesReceiptJson.getTouristInfoDTOList();
                    if (CollectionUtils.isNotEmpty(touristInfoDTOList)){
                        List<String> touristNameList = new ArrayList<>();
                        touristInfoDTOList.forEach(receiptInfo -> {
                            touristNameList.add(receiptInfo.getCnFullname());
                        });
                        receipt.setTouristNameList(touristNameList);
                    }
                }
            }else{
                //保单收据
                QueryWrapper<CustomizedOrderInsurance> insuranceQueryWrapper = new QueryWrapper<>();
                insuranceQueryWrapper.eq("receipt_id",receipt.getId());
                insuranceQueryWrapper.eq("order_id",receipt.getOrderId());
                insuranceQueryWrapper.eq("is_deleted",0);
                CustomizedOrderInsurance insurance = orderInsuranceMapper.selectOne(insuranceQueryWrapper);
                if (insurance == null){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4028);
                }
                //保单收据
                QueryWrapper<CustomizedOrderReceiptInsurance> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("insurance_id",insurance.getId());
                queryWrapper1.eq("order_id",receipt.getOrderId());
                queryWrapper1.eq("is_deleted",0);
                CustomizedOrderReceiptInsurance receiptInsurance = orderReceiptInsuranceMapper.selectOne(queryWrapper1);
                if (receiptInsurance == null){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4024);
                }
                //旅客列表
                QueryWrapper<CustomizedOrderInsurancePriceTourist> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("insurance_id",receiptInsurance.getInsuranceId());
                List<CustomizedOrderInsurancePriceTourist> list = orderInsurancePriceTouristMapper.selectList(queryWrapper2);
                if (list != null && list.size() > 0){
                    List<String> touristNameList = new ArrayList<>();
                    for (CustomizedOrderInsurancePriceTourist tourist : list){
                        touristNameList.add(tourist.getEnSurname()+tourist.getEnName());
                    }
                    receipt.setTouristNameList(touristNameList);
                }
            }
        });
        PageResponse<CustomOrderReceiptListDTO> pageResponse = new PageResponse<>(pageResult.getRecords(),
                pageResult.getCurrent() == 1,
                pageResult.getTotal() <= (pageResult.getCurrent() * pageResult.getSize()),
                pageResult.getTotal(), pageResult.getCurrent(),
                pageResult.getSize());
        dto.setPage(pageResponse);
        return dto;
    }

    /**
     * 打印收據-旅客列表
     *
     * @param req
     * @return
     */
    @Override
    public CustomOrderReceiptListTouristDTO listPrint(CustomOrderReceiptListTouristReq req) {
        CustomOrderReceiptListTouristDTO dto = orderReceiptMapper.selectCountListTouristBySelective(req);
        if (dto == null) {
            dto = new CustomOrderReceiptListTouristDTO();
        }
        IPage<CustomOrderReceiptListTouristReq> pageParam = new Page<>(req.getPageNo(), req.getPageSize());
        IPage<CustomOrderReceiptListTouristPageDTO> pageResult = orderReceiptMapper.selectListTouristBySelective(pageParam, req);
        PageResponse<CustomOrderReceiptListTouristPageDTO> pageResponse = new PageResponse<>(pageResult.getRecords(),
                pageResult.getCurrent() == 1,
                pageResult.getTotal() <= (pageResult.getCurrent() * pageResult.getSize()),
                pageResult.getTotal(), pageResult.getCurrent(),
                pageResult.getSize());
        dto.setPage(pageResponse);
        return dto;
    }

    /**
     * 销售收据预览
     *
     * @param req
     * @return
     */
    @Override
    public Result<CustomOrderReceiptDetailsPreviewDTO> preview(CustomOrderReceiptDetailsPreviewReq req) {
        System.out.println("销售收据预览 req =====>>> "+req.toString());
        CustomOrderReceiptDetailsPreviewDTO detailsPreviewDTO = new CustomOrderReceiptDetailsPreviewDTO();
        detailsPreviewDTO.setId(IdWorker.getId());
        detailsPreviewDTO.setOrderId(req.getOrderId());
        detailsPreviewDTO.setScheduleId(req.getScheduleId());
        detailsPreviewDTO.setDataSource(req.getDataSource());
        //销售收据
        CustomizedTripScheduleDTO tripScheduleDTO = tripScheduleService.queryByScheduleId(req.getScheduleId());
        List<CustomOrderReceiptDetailsPreviewItemDTO> itemDTOList = new ArrayList<>();
        List<CustomOrderReceiptDetailsPreviewRemarkDTO> remarkDTOList = new ArrayList<>();
        Set<Long> touristIdList = new HashSet<>();
        Long firstTouristId = null;
        List<CustomizedOrderCollection> items = new ArrayList<>();
        if (Objects.equals(DataSourceCode.COLLECTION.getCode(), req.getDataSource())) {
            //收款
            items.addAll(orderCollectionMapper.selectBatchIds(req.getIdList()));
            for (int i = 0; i < items.size(); i++) {
                CustomizedOrderCollection collection = items.get(i);
                if (i == 0) {
                    firstTouristId = collection.getTouristId();
                }
                touristIdList.add(collection.getTouristId());
            }
        } else if (Objects.equals(DataSourceCode.RECEIPT.getCode(), req.getDataSource())) {
            //收据
            for (Long id : req.getIdList()) {
                QueryWrapper<CustomizedOrderCollection> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(CustomizedOrderCollection::getOrderId, req.getOrderId());
                queryWrapper.lambda().eq(CustomizedOrderCollection::getTouristId, id);
                queryWrapper.lambda().eq(CustomizedOrderCollection::getIsPrint, 0);
                List<CustomizedOrderCollection> collectionList = orderCollectionMapper.selectList(queryWrapper);
                items.addAll(collectionList);
            }
            firstTouristId = req.getIdList().get(0);
            //游客id
            touristIdList.addAll(req.getIdList());
        }
        //代收费用
        BigDecimal receiptCollectionFee = new BigDecimal(0);
        //调整费用
        BigDecimal receiptAdjustmentCost = new BigDecimal(0);
        //其他
        BigDecimal receiptOtherAmount = new BigDecimal(0);
        //团费
        BigDecimal receiptGroupFee = new BigDecimal(0);
        //總應付
        BigDecimal receiptTotalReceivables = new BigDecimal(0);
        //已付
        BigDecimal receiptPaidAmount = new BigDecimal(0);
        //現付
        BigDecimal receiptPayAmount = new BigDecimal(0);
        //餘款
        BigDecimal receiptRemainingAmount = new BigDecimal(0);
        Map<Long, CustomizedOrderTouristInfo> cache = new HashMap<>();
        for (Long id : touristIdList) {
            CustomizedOrderTouristInfo touristInfo = null;
            if (cache.get(id) == null) {
                touristInfo = orderTouristInfoMapper.selectById(id);
                if (!Objects.equals(touristInfo.getIsDeleted(),NumberConstant.ONE.getValue())){
                    cache.put(id, touristInfo);
                }
            } else {
                touristInfo = cache.get(id);
            }
            if (touristInfo == null) {
                throw new BusinessException(SystemError.SYS_411);
            }
            //收款项
            CustomOrderReceiptDetailsPreviewItemDTO itemDTO = EntityUtil.copy(touristInfo, CustomOrderReceiptDetailsPreviewItemDTO.class);
            itemDTO.setTouristId(id);
            itemDTO.setPaidAmount(touristInfo.getReceiptedAmount());
            //代收费用
            BigDecimal collectionFee = new BigDecimal(0);
            //调整费用
            BigDecimal adjustmentCost = new BigDecimal(0);
            //其他
            BigDecimal otherAmount = new BigDecimal(0);
            //团费
            BigDecimal groupFee = new BigDecimal(0);
            //總應付
            BigDecimal totalReceivables = new BigDecimal(0);
            //已付
            BigDecimal paidAmount = new BigDecimal(0);
            //現付
            BigDecimal payAmount = new BigDecimal(0);
            //餘款
            BigDecimal remainingAmount = new BigDecimal(0);
            for (CustomizedOrderCollection item : items) {
                if (Objects.equals(item.getTouristId(), id)) {
                    payAmount = payAmount.add(item.getPaidInAmount());
                    //收款方式銀行優惠、優惠、積分作為減免項
                    if (Objects.equals(item.getCollectionWayId(), CollectionRefundWayIdCode.BANK_PREFERENCE.getCode())
                            || Objects.equals(item.getCollectionWayId(), CollectionRefundWayIdCode.POINTS.getCode())
                            || Objects.equals(item.getCollectionWayId(), CollectionRefundWayIdCode.OPERATE_PROMOTION.getCode())) {
                        otherAmount = otherAmount.subtract(item.getPaidInAmount());
                    }
                }
            }
            //現付 = 所有收款累计
            itemDTO.setPayAmount(payAmount);
            //餘數=總應付-已付-現付
            remainingAmount = itemDTO.getTotalReceivables().subtract(
                    touristInfo.getReceiptedAmount()).subtract(payAmount);
            itemDTO.setRemainingAmount(remainingAmount);
            itemDTOList.add(itemDTO);

            //代收费用
            receiptCollectionFee = receiptCollectionFee.add(collectionFee);
            //调整费用
            receiptAdjustmentCost = receiptAdjustmentCost.add(adjustmentCost);
            //其他
            receiptOtherAmount = receiptOtherAmount.add(otherAmount);
            //团费
            receiptGroupFee = receiptGroupFee.add(groupFee);
            //總應付
            receiptTotalReceivables = receiptTotalReceivables.add(totalReceivables);
            //已付
            receiptPaidAmount = receiptPaidAmount.add(paidAmount);
            //現付
            receiptPayAmount = receiptPayAmount.add(payAmount);
            //餘款
            receiptRemainingAmount = receiptRemainingAmount.add(remainingAmount);
            //备注
            CustomOrderReceiptDetailsPreviewRemarkDTO remarkDTO = EntityUtil.copy(touristInfo, CustomOrderReceiptDetailsPreviewRemarkDTO.class);
            LocalDate now = LocalDate.now();
            Period between1 = null;
            Period between2 = null;
            Period between3 = null;
            if (touristInfo.getCertificateValidDate() != null) {
                between1 = Period.between(now, touristInfo.getCertificateValidDate());
            }
            if (touristInfo.getCertificateValidDate2() != null) {
                between2 = Period.between(now, touristInfo.getCertificateValidDate2());
            }
            if (touristInfo.getCertificateValidDate3() != null) {
                between3 = Period.between(now, touristInfo.getCertificateValidDate3());
            }
            if ((between1 != null && between1.getDays() <= 60) || (between2 != null && between2.getDays() <= 60) || (between3 != null && between3.getDays() <= 60)) {
                remarkDTO.setIsInsufficient(ISCode.YES.getCode());
            } else {
                remarkDTO.setIsInsufficient(ISCode.NO.getCode());
            }
            //备注项目
            List<CustomOrderReceiptDetailsPreviewRemarkProjectDTO> projectDTOList = new ArrayList<>();
            //团费
            CustomOrderReceiptDetailsPreviewRemarkProjectDTO groupProjectDTO = new CustomOrderReceiptDetailsPreviewRemarkProjectDTO();
            groupProjectDTO.setName(StrConstant.GROUP_FEE.getValue());
            groupProjectDTO.setAmount(touristInfo.getGroupFee());
            projectDTOList.add(groupProjectDTO);
            //代收费用
            QueryWrapper<CustomizedOrderTouristOtherFee> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(CustomizedOrderTouristOtherFee::getOrderId, req.getOrderId());
            queryWrapper.lambda().eq(CustomizedOrderTouristOtherFee::getTouristId, id);
            queryWrapper.lambda().and(object -> object.eq(CustomizedOrderTouristOtherFee::getFeeType, SeriesOrderTouristOtherFeeFeeTypeCode.COLLECTION.getCode())
                    .or().eq(CustomizedOrderTouristOtherFee::getFeeType, SeriesOrderTouristOtherFeeFeeTypeCode.OTHER.getCode()));
            queryWrapper.lambda().eq(CustomizedOrderTouristOtherFee::getIsDeleted, IsDeletedCode.NO.getCode());
            List<CustomizedOrderTouristOtherFee> collectionFeeList = orderTouristOtherFeeMapper.selectList(queryWrapper);
            for (CustomizedOrderTouristOtherFee fee : collectionFeeList) {
                if (Objects.equals(fee.getFeeType(), SeriesOrderTouristOtherFeeFeeTypeCode.COLLECTION.getCode())) {
                    CustomOrderReceiptDetailsPreviewRemarkProjectDTO remarkProjectDTO = new CustomOrderReceiptDetailsPreviewRemarkProjectDTO();
                    remarkProjectDTO.setName(fee.getFeeName());
                    remarkProjectDTO.setAmount(fee.getAmount());
                    projectDTOList.add(remarkProjectDTO);
                }
            }
            //调整费用
            QueryWrapper<CustomizedOrderTouristFeeAdjust> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.lambda().eq(CustomizedOrderTouristFeeAdjust::getOrderId, req.getOrderId());
            queryWrapper2.lambda().eq(CustomizedOrderTouristFeeAdjust::getTouristId, id);
            queryWrapper2.lambda().eq(CustomizedOrderTouristFeeAdjust::getAdjustType, 1);
            List<CustomizedOrderTouristFeeAdjust> adjustFeeList = orderTouristFeeAdjustMapper.selectList(queryWrapper2);
            for (CustomizedOrderTouristFeeAdjust adjustFee : adjustFeeList) {
                CustomOrderReceiptDetailsPreviewRemarkProjectDTO remarkProjectDTO = new CustomOrderReceiptDetailsPreviewRemarkProjectDTO();
                remarkProjectDTO.setName(adjustFee.getName());
                remarkProjectDTO.setAmount(adjustFee.getAmount());
                remarkProjectDTO.setPlusType(adjustFee.getPlusType());
                projectDTOList.add(remarkProjectDTO);
            }
            //其他
            QueryWrapper<CustomizedOrderCollection> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.lambda().eq(CustomizedOrderCollection::getOrderId, req.getOrderId());
            queryWrapper3.lambda().eq(CustomizedOrderCollection::getTouristId, id);
            queryWrapper3.lambda().and(object -> object.eq(CustomizedOrderCollection::getCollectionWayId, CollectionRefundWayIdCode.BANK_PREFERENCE.getCode())
                    .or().eq(CustomizedOrderCollection::getCollectionWayId, CollectionRefundWayIdCode.POINTS.getCode())
                    .or().eq(CustomizedOrderCollection::getCollectionWayId, CollectionRefundWayIdCode.OPERATE_PROMOTION.getCode()));
            queryWrapper3.lambda().eq(CustomizedOrderCollection::getIsDeleted, IsDeletedCode.NO.getCode());
            List<CustomizedOrderCollection> collectionList = orderCollectionMapper.selectList(queryWrapper3);
            for (CustomizedOrderCollection collection : collectionList) {
                if (Objects.equals(collection.getCollectionWayId(), CollectionRefundWayIdCode.BANK_PREFERENCE.getCode())) {
                    CustomOrderReceiptDetailsPreviewRemarkProjectDTO remarkProjectDTO = new CustomOrderReceiptDetailsPreviewRemarkProjectDTO();
                    remarkProjectDTO.setName(CollectionRefundWayIdCode.BANK_PREFERENCE.getMsg2());
                    remarkProjectDTO.setAmount(collection.getPaidInAmount());
                    remarkProjectDTO.setPlusType(2);
                    projectDTOList.add(remarkProjectDTO);
                } else if (Objects.equals(collection.getCollectionWayId(), CollectionRefundWayIdCode.POINTS.getCode())) {
                    CustomOrderReceiptDetailsPreviewRemarkProjectDTO remarkProjectDTO = new CustomOrderReceiptDetailsPreviewRemarkProjectDTO();
                    remarkProjectDTO.setName(CollectionRefundWayIdCode.POINTS.getMsg2());
                    remarkProjectDTO.setAmount(collection.getPaidInAmount());
                    remarkProjectDTO.setPlusType(2);
                    projectDTOList.add(remarkProjectDTO);
                } else if (Objects.equals(collection.getCollectionWayId(), CollectionRefundWayIdCode.OPERATE_PROMOTION.getCode())) {
                    CustomOrderReceiptDetailsPreviewRemarkProjectDTO remarkProjectDTO = new CustomOrderReceiptDetailsPreviewRemarkProjectDTO();
                    remarkProjectDTO.setName(CollectionRefundWayIdCode.OPERATE_PROMOTION.getMsg2());
                    remarkProjectDTO.setAmount(collection.getPaidInAmount());
                    remarkProjectDTO.setPlusType(2);
                    projectDTOList.add(remarkProjectDTO);
                }
            }
            for (CustomizedOrderTouristOtherFee fee : collectionFeeList) {
                if (Objects.equals(fee.getFeeType(), SeriesOrderTouristOtherFeeFeeTypeCode.OTHER.getCode()) &&
                        Objects.equals(fee.getFeeName(), StrConstant.DISCOUNT.getValue())) {
                    CustomOrderReceiptDetailsPreviewRemarkProjectDTO remarkProjectDTO = new CustomOrderReceiptDetailsPreviewRemarkProjectDTO();
                    remarkProjectDTO.setName(fee.getFeeName());
                    remarkProjectDTO.setAmount(fee.getAmount());
                    remarkProjectDTO.setPlusType(1);
                    projectDTOList.add(remarkProjectDTO);
                }
            }

            remarkDTO.setProjectList(projectDTOList);
            remarkDTOList.add(remarkDTO);
        }

        //付款方式
        Map<Long, CustomOrderReceiptDetailsPreviewWayDTO> wayMap = new HashMap<>();
        List<Long> collectionIdList = new ArrayList<>();
        for (CustomizedOrderCollection item : items) {
            CustomOrderReceiptDetailsPreviewWayDTO wayDTO = wayMap.get(item.getCollectionWayId());
            if (wayDTO == null) {
                wayDTO = EntityUtil.copy(item, CustomOrderReceiptDetailsPreviewWayDTO.class);
                wayDTO.setItemList(new ArrayList<>());
                wayMap.put(item.getCollectionWayId(), wayDTO);
            } else {
                CustomOrderReceiptDetailsPreviewWayItemDTO wayItemDTO = EntityUtil.copy(item, CustomOrderReceiptDetailsPreviewWayItemDTO.class);
                wayDTO.getItemList().add(wayItemDTO);
            }
            collectionIdList.add(item.getId());
        }
        List<CustomOrderReceiptDetailsPreviewWayDTO> wayDTOList = new ArrayList<>();
        for (Long key : wayMap.keySet()) {
            wayDTOList.add(wayMap.get(key));
        }

        CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(firstTouristId);

        detailsPreviewDTO.setCustomerRights(tripScheduleDTO.getCustomerRights());
//        detailsPreviewDTO.setTeaPartyLocName(seriesTripScheduleTeamRuleDTO.getTeaPartyLocId());
        if (tripScheduleDTO.getAdvancedDTO() != null){
            detailsPreviewDTO.setTeaPartyDate(tripScheduleDTO.getAdvancedDTO().getTeaPartyDate());
            detailsPreviewDTO.setTeaPartyTime(tripScheduleDTO.getAdvancedDTO().getTeaPartyTime());
        }
//        noticeAddReq.setCompanyNotes();
        if (StringUtils.isNotBlank(touristInfo.getEnSurname()) && StringUtils.isNotBlank(touristInfo.getEnName())) {
            if (StringUtils.isNotBlank(touristInfo.getCnSurname()) && StringUtils.isNotBlank(touristInfo.getCnName())) {
                detailsPreviewDTO.setTouristName(touristInfo.getEnSurname() + " " + touristInfo.getEnName() +
                        "(" + touristInfo.getCnSurname() + " " + touristInfo.getCnName() + ")");
            } else {
                detailsPreviewDTO.setTouristName(touristInfo.getEnSurname() + " " + touristInfo.getEnName());
            }
        } else {
            if (StringUtils.isNotBlank(touristInfo.getCnSurname()) && StringUtils.isNotBlank(touristInfo.getCnName())) {
                detailsPreviewDTO.setTouristName(touristInfo.getCnSurname() + " " + touristInfo.getCnName());
            }
        }
//        noticeAddReq.setAgent();
//        collectionAddDTO.setMantissaDate(seriesTripScheduleTeamRuleDTO.getDeliveryDays());
        detailsPreviewDTO.setTourCode(tripScheduleDTO.getTripNumber());
        detailsPreviewDTO.setDays(tripScheduleDTO.getTravelDays());
        detailsPreviewDTO.setDepDate(CharUtil.getWeekDay(tripScheduleDTO.getDepartureDate().getDayOfWeek().getValue()));
        detailsPreviewDTO.setRoute(tripScheduleDTO.getName());
        detailsPreviewDTO.setEnquiryNo(OrderUtil.getRandom6());
        detailsPreviewDTO.setEnquiryTimeTel(Constants.QUERY_TIME);
        detailsPreviewDTO.setItemList(itemDTOList);
        detailsPreviewDTO.setWayList(wayDTOList);
        detailsPreviewDTO.setRemarkList(remarkDTOList);
        detailsPreviewDTO.setCollectionIdList(collectionIdList);
        detailsPreviewDTO.setReceiptNumber(OrderUtil.getReceiptNumberB());
        //代收费用
        detailsPreviewDTO.setCollectionFee(receiptCollectionFee);
        //调整费用
        detailsPreviewDTO.setAdjustmentCost(receiptAdjustmentCost);
        //其他
        detailsPreviewDTO.setOtherAmount(receiptOtherAmount);
        //团费
        detailsPreviewDTO.setGroupFee(receiptGroupFee);
        //總應付
        detailsPreviewDTO.setTotalReceivables(receiptTotalReceivables);
        //已付
        detailsPreviewDTO.setPaidAmount(receiptPaidAmount);
        //現付
        detailsPreviewDTO.setPayAmount(receiptPayAmount);
        //餘款
        detailsPreviewDTO.setRemainingAmount(receiptRemainingAmount);
        //定制包团须知
        detailsPreviewDTO.setTourFeeInclude(tripScheduleDTO.getTourFeeInclude());
        detailsPreviewDTO.setTourFeeExclude(tripScheduleDTO.getTourFeeExclude());
        detailsPreviewDTO.setSignNotice(tripScheduleDTO.getSignNotice());
        detailsPreviewDTO.setRemark(tripScheduleDTO.getRemark());
        return Result.success(detailsPreviewDTO);
    }


    /**
     * 查看收據
     *
     * @param req
     * @return
     */
    @Override
    public Result<CustomOrderReceiptInfoDTO> detail(CustomOrderReceiptDetailsIdReq req) {
        CustomizedOrderReceipt receipt = getById(req.getId());
        if (receipt == null || Objects.equals(receipt.getIsDeleted(),NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4024);
        }
        CustomOrderReceiptInfoDTO dto = new CustomOrderReceiptInfoDTO();
        dto.setReceiptType(receipt.getReceiptType());
        CustomizedTripScheduleDTO tripSchedule = tripScheduleService.queryByScheduleId(receipt.getScheduleId());
        if (receipt.getReceiptType().intValue() == NumberConstant.ONE.getValue()){
            //销售收据
            QueryWrapper<CustomizedOrderReceiptDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("receipt_id",req.getId());
            queryWrapper.eq("order_id",receipt.getOrderId());
            queryWrapper.eq("receipt_status",1);
            CustomizedOrderReceiptDetails receiptDetails = orderReceiptDetailsMapper.selectOne(queryWrapper);
            if (receiptDetails == null){
                throw new BusinessException(SystemError.CUSTOM_ORDER_4024);
            }
            CustomOrderReceiptDetailsPreviewDTO salesReceipt = EntityUtil.copy(receiptDetails,CustomOrderReceiptDetailsPreviewDTO.class);
            if (StringUtils.isNotBlank(receiptDetails.getReceipJson())){
                SalesReceiptJson salesReceiptJson = JSON.parseObject(receiptDetails.getReceipJson(), SalesReceiptJson.class);
                salesReceipt = EntityUtil.copy(salesReceiptJson,CustomOrderReceiptDetailsPreviewDTO.class);
            }
            salesReceipt.setId(receiptDetails.getId());
            salesReceipt.setTouristName(receiptDetails.getTouristName());
            salesReceipt.setCustomerRights(receiptDetails.getCustomerRights());
            salesReceipt.setCompanyNotes(receiptDetails.getCompanyNotes());
            salesReceipt.setTeaPartyDate(receiptDetails.getTeaPartyDate());
            salesReceipt.setTeaPartyTime(receiptDetails.getTeaPartyTime());
            salesReceipt.setTeaPartyLocName(receiptDetails.getTeaPartyLocName());
            if (tripSchedule.getDeliveryDays() != null){
                salesReceipt.setMantissaDate(tripSchedule.getGmtCreate().plusDays(tripSchedule.getDeliveryDays().longValue()).toLocalDate());
            }
            salesReceipt.setStampDutyPic(receiptDetails.getStampDutyPic());
            salesReceipt.setIsPrint(receiptDetails.getIsPrint());
            if (receipt.getCreateId() != null){
                UserDTO userDTO = sysUserService.queryCacheUser(receipt.getCreateId());
                if (userDTO != null){
                    salesReceipt.setAgent(userDTO.getDeptCode());
                }
            }
            dto.setSalesReceipt(salesReceipt);
        }else{
            QueryWrapper<CustomizedOrderInsurance> insuranceQueryWrapper = new QueryWrapper<>();
            insuranceQueryWrapper.eq("receipt_id",req.getId());
            insuranceQueryWrapper.eq("order_id",receipt.getOrderId());
            insuranceQueryWrapper.eq("is_deleted",0);
            CustomizedOrderInsurance insurance = orderInsuranceMapper.selectOne(insuranceQueryWrapper);
            if (insurance == null){
                throw new BusinessException(SystemError.CUSTOM_ORDER_4028);
            }
            //保单收据
            QueryWrapper<CustomizedOrderReceiptInsurance> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("insurance_id",insurance.getId());
            queryWrapper.eq("order_id",receipt.getOrderId());
            queryWrapper.eq("is_deleted",0);
            CustomizedOrderReceiptInsurance receiptInsurance = orderReceiptInsuranceMapper.selectOne(queryWrapper);
            if (receiptInsurance == null){
                throw new BusinessException(SystemError.CUSTOM_ORDER_4024);
            }
            PreviewInsuranceReceiptCompatibleDTO insuranceReceipt = EntityUtil.copy(receiptInsurance, PreviewInsuranceReceiptCompatibleDTO.class);

            //兼容旅行团保单收据字段
            insuranceReceipt.setAgent(receiptInsurance.getDeptCode());
            insuranceReceipt.setMantissaDate(receiptInsurance.getDeliveryDate());
            insuranceReceipt.setTourCode(receiptInsurance.getTripNumber());
            insuranceReceipt.setTourCode(receiptInsurance.getDepartDate());
            insuranceReceipt.setRoute(receiptInsurance.getItinerary());
            insuranceReceipt.setReceiptDate(receiptInsurance.getCreateDate());

            insuranceReceipt.setDepDate(receiptInsurance.getDepartDate());

            //旅客列表
            QueryWrapper<CustomizedOrderInsurancePriceTourist> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("insurance_id",receiptInsurance.getInsuranceId());
            List<CustomizedOrderInsurancePriceTourist> list = orderInsurancePriceTouristMapper.selectList(queryWrapper2);
            if (list != null && list.size() > 0){
                List<InsuranceTouristDTO> touristList = new ArrayList<>();
                for (CustomizedOrderInsurancePriceTourist tourist : list){
                    InsuranceTouristDTO touristDTO = EntityUtil.copy(tourist, InsuranceTouristDTO.class);
                    touristList.add(touristDTO);
                }
                insuranceReceipt.setInsuredList(touristList);
            }
            dto.setInsuranceReceiptCompatible(insuranceReceipt);
        }
        return Result.success(dto);
    }


    /**
     * 重印收據
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<CustomOrderReceiptDetailsPreviewDTO> rePrint(CustomOrderReceiptDetailsRePrintReq req) {
        CustomizedOrderReceiptDetails receiptDetails = orderReceiptDetailsMapper.selectById(req.getId());
        if (receiptDetails == null) {
            throw new BusinessException(SystemError.SYS_411);
        }
        CustomizedOrderReceipt dbReceipt = orderReceiptMapper.selectById(receiptDetails.getReceiptId());
        if (dbReceipt == null || Objects.equals(dbReceipt.getIsDeleted(),NumberConstant.ONE.getValue())) {
            throw new BusinessException(SystemError.SYS_411);
        }
        if (!Objects.equals(dbReceipt.getReceiptStatus(), NumberConstant.ONE.getValue())) {
            throw new BusinessException(SystemError.CUSTOM_ORDER_4018);
        }
        CustomOrderReceiptDetailsPreviewDTO dto = null;
        //判断是否修改
        if (!Objects.equals(req.getTouristName(), receiptDetails.getTouristName())) {
            throw new BusinessException(SystemError.CUSTOM_ORDER_4051);
        }
        dbReceipt.setReceiptHeader(req.getTouristName());
        dbReceipt.setCreateTime(LocalDateTime.now());
        dbReceipt.setModifiedId(req.getUserId());
        int updateById = orderReceiptMapper.updateById(dbReceipt);
        if (updateById <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        if (StringUtils.isNotBlank(receiptDetails.getReceipJson())) {
            dto = JSON.parseObject(receiptDetails.getReceipJson(), CustomOrderReceiptDetailsPreviewDTO.class);
            if (dto != null) {
                dto.setTouristName(req.getTouristName());
            }
            receiptDetails.setReceipJson(JSON.toJSONString(dto));
        }
        receiptDetails.setTouristName(req.getTouristName());
        int update = orderReceiptDetailsMapper.updateById(receiptDetails);
        if (update <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(dto);
    }

    /**
     * 收據作废
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result invalid(CustomOrderReceiptInvalidReq req) {
        CustomizedOrderReceipt receipt = getById(req.getId());
        if (receipt == null || Objects.equals(receipt.getIsDeleted(),NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4024);
        }
        if (receipt.getReceiptType().intValue() == NumberConstant.TWO.getValue()){
            //保单收据不可作废
            throw new BusinessException(SystemError.CUSTOM_ORDER_4040);
        }
        if (receipt.getReceiptStatus().intValue() == NumberConstant.ZERO.getValue()){
            //该收据已作废
            throw new BusinessException(SystemError.CUSTOM_ORDER_4041);
        }
        //收据作废
        LocalDateTime now = LocalDateTime.now();
        receipt.setVoidTime(now);
        receipt.setVoidReason(req.getVoidReason());
        receipt.setGmtModified(now);
        receipt.setModifiedId(req.getUserId());
        receipt.setReceiptStatus(0);
        int update1 = orderReceiptMapper.updateById(receipt);
        //销售收据作废
        QueryWrapper<CustomizedOrderReceiptDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("receipt_id",req.getId());
        queryWrapper.eq("order_id",receipt.getOrderId());
        queryWrapper.eq("receipt_status",1);
        CustomizedOrderReceiptDetails receiptDetails = orderReceiptDetailsMapper.selectOne(queryWrapper);
        if (receiptDetails == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4024);
        }
        receiptDetails.setReceiptStatus(0);
        int update2 = orderReceiptDetailsMapper.updateById(receiptDetails);
        if (update1 <= 0 || update2 <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //回滚收款记录isPrint
        if (StringUtils.isNotBlank(receiptDetails.getReceipJson())){
            SalesReceiptJson salesReceiptJson = JSON.parseObject(receiptDetails.getReceipJson(), SalesReceiptJson.class);
            List<Long> collectionIdList = salesReceiptJson.getCollectionIdList();
            if (CollectionUtils.isNotEmpty(collectionIdList)){
                //更新关联收款记录是否开收据状态
                collectionIdList.forEach(collectionId -> {
                    CustomizedOrderCollection collection = orderCollectionMapper.selectById(collectionId);
                    if (collection != null && Objects.equals(collection.getIsDeleted(),0)){
                        collection.setIsPrint(0);
                        collection.setModifiedId(req.getUserId());
                        int update = orderCollectionMapper.updateById(collection);
                        if (update <= 0){
                            throw new BusinessException(SystemError.SYS_408);
                        }
                    }
                });
            }
        }
        //旅客统计
        QueryWrapper<CustomizedOrderReceiptTourist> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().eq(CustomizedOrderReceiptTourist::getReceiptId, receipt.getId());
        queryWrapper2.lambda().eq(CustomizedOrderReceiptTourist::getOrderId, receipt.getOrderId());
        List<CustomizedOrderReceiptTourist> receiptTouristList = orderReceiptTouristMapper.selectList(queryWrapper2);
        //已出单据金额
        BigDecimal orderReceiptedAmount = new BigDecimal(0);
        for (CustomizedOrderReceiptTourist receiptTourist : receiptTouristList) {
            CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(receiptTourist.getTouristId());
            if (touristInfo == null || Objects.equals(touristInfo.getIsDeleted(),NumberConstant.ONE.getValue())) {
                throw new BusinessException(SystemError.SYS_411);
            }
            //已出单据金额
            BigDecimal receiptedAmount = touristInfo.getReceiptedAmount().subtract(receiptTourist.getReceiptAmount());
            touristInfo.setReceiptedAmount(receiptedAmount);
            touristInfo.setModifiedId(req.getUserId());
            //更新旅客统计
            int update3 = orderTouristInfoMapper.updateById(touristInfo);
            if (update3 <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
            orderReceiptedAmount = orderReceiptedAmount.add(receiptedAmount);
        }
        //更新关联收款记录是否开收据状态
//        orderCollectionService.batchUpdateIsPrint(receipt.getId(),receipt.getOrderId(),req.getUserId());
        if (StringUtils.isNotBlank(receiptDetails.getStampDutyPic())){
            //对接财务中心印花税退款 -> 新增记录
            List<StampTaxRefundAddReq> reqList = new ArrayList<>();
            CustomizedOrder order = orderMapper.selectById(receipt.getOrderId());
            //封装财务退印花税请求参数
            StampTaxRefundAddReq addReq = packStampTaxRefundAddReq(order,receipt,now,req.getUserId(),receiptDetails.getStampDutyAmount());
            reqList.add(addReq);
            Result result = financeStampTaxRefundService.add(reqList, req.getUserId());
            if (result == null || result.getCode() != 0){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        return Result.success(req.getId());
    }

    /**
     * 封装财务退印花税请求参数
     * @param order
     * @param receipt
     * @param now
     * @param userId
     * @return
     */
    private StampTaxRefundAddReq packStampTaxRefundAddReq(CustomizedOrder order,CustomizedOrderReceipt receipt,LocalDateTime now,Long userId,BigDecimal taxAmount){
        StampTaxRefundAddReq addReq = new StampTaxRefundAddReq();
        addReq.setReceiptNumber(receipt.getReceiptNumber());
        addReq.setBusinessType(SystemBusinessType.OUTBOUND_CUSTOMIZATION.getCode());
        addReq.setOrderSource(order.getOrderSource());
        addReq.setCancelTime(now);
        addReq.setRefundNumber(order.getOrderNumber());
        addReq.setTaxAmount(taxAmount);
        addReq.setProductId(order.getScheduleId());
        CustomizedTripScheduleDTO tripScheduleDTO = tripScheduleService.queryByScheduleId(order.getScheduleId());
        addReq.setProductNumber(tripScheduleDTO.getTripNumber());
        addReq.setResourceInfo(tripScheduleDTO.getName());
        UserDTO userDTO = sysUserService.queryCacheUser(userId);
        addReq.setSaleUserId(userId);
        addReq.setSaleUserName(userDTO.getFullName());
        addReq.setDepartment(userDTO.getDept());
        addReq.setDepartmentId(userDTO.getDeptId());
        return addReq;
    }

    /**
     * 打印整單收據
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result invalidAll(OrderReceiptPrintAllReq req) {
        CustomizedOrder order = orderMapper.selectById(req.getOrderId());
        if (order == null || Objects.equals(order.getIsDeleted(),NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
        }
        //修改订单统计
        QueryWrapper<CustomizedOrderAmountStatistics> statisticsWrapper = new QueryWrapper<>();
        statisticsWrapper.eq("order_id",req.getOrderId());
        CustomizedOrderAmountStatistics statistics = orderAmountStatisticsMapper.selectOne(statisticsWrapper);
        if (statistics == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
        }
        statistics.setReceiptedAmount(BigDecimal.ZERO);
        //获取团期信息
        CustomizedTripScheduleDTO tripSchedule = tripScheduleService.queryByScheduleId(statistics.getScheduleId());
        if (tripSchedule == null){
            throw new BusinessException(SystemError.CUSTOM_3006);
        }

        //是否计算印花税
        boolean isTax = false;
        if(Objects.equals(Constants.AREA_HK, tripSchedule.getDeparturePlaceId()) && !Objects.equals(Constants.AREA_HK, tripSchedule.getDestinationId())) {
            isTax = true;
        }

        //清空收据关联旅客
        orderReceiptTouristMapper.cleanByOrder(order.getId(),req.getUserId());

        LocalDateTime now = LocalDateTime.now();
        //收款方式
        List<String> payMethodList = new ArrayList<>();
        //收款方
        List<String> payerList = new ArrayList<>();
        //收款ID列表
        List<Long> collectionIdList = new ArrayList<>();
        //旅客信息
        List<ReceiptTouristInfoDTO> touristInfoDTOList = new ArrayList<>();
        //旅客收据详情列表
        List<TouristReceiptInfoDTO> touristReceiptInfoList = new ArrayList<>();
        //财务退印花税请求参数List
        List<StampTaxRefundAddReq> reqList = new ArrayList<>();
        //旅客列表
        QueryWrapper<CustomizedOrderTouristInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",req.getOrderId());
        queryWrapper.eq("is_full_info",1);
        queryWrapper.eq("is_deleted",0);
        List<CustomizedOrderTouristInfo> touristInfoList1 = orderTouristInfoMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(touristInfoList1)){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
        }
        for (CustomizedOrderTouristInfo touristInfo : touristInfoList1) {
            //判断出发地是否香港，是 -> 计算印花税
            if (isTax && touristInfo.getTotalPaidIn().compareTo(BigDecimal.ZERO) > 0){
                touristInfo.setIsReceiptCalculated(1);
            }else{
                touristInfo.setIsReceiptCalculated(0);
            }
            touristInfo.setModifiedId(req.getUserId());
            //重置
            touristInfo.setReceiptedAmount(BigDecimal.ZERO);
            int updateTouristInfo = orderTouristInfoMapper.updateById(touristInfo);
            if (updateTouristInfo <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
            //收据旅客信息
            ReceiptTouristInfoDTO touristInfoDTO = EntityUtil.copy(touristInfo,ReceiptTouristInfoDTO.class);
            touristInfoDTO.setPayAmount(touristInfo.getTotalPaidIn());
            touristInfoDTOList.add(touristInfoDTO);
        }

        //数据抬头
        Long firstTouristId = touristInfoDTOList.get(0).getId();
        CustomizedOrderTouristInfo firstTourist = orderTouristInfoMapper.selectById(firstTouristId);
        String receiptHeader = tripSchedule.getChargePersonName();
        if (StringUtils.isNotBlank(firstTourist.getCnFullname())){
            receiptHeader = firstTourist.getCnFullname();
        }else{
            receiptHeader = firstTourist.getEnFullname();
        }

        //订单收款记录
        QueryWrapper<CustomizedOrderCollection> collectionQueryWrapper = new QueryWrapper<>();
        collectionQueryWrapper.eq("order_id",req.getOrderId());
        collectionQueryWrapper.eq("is_deleted",0);
        List<CustomizedOrderCollection> collectionList = orderCollectionMapper.selectList(collectionQueryWrapper);
        //印花税金额
        BigDecimal stampDutyAmount = BigDecimal.ZERO;
        //收款总金额
        BigDecimal totalCollectionAmount = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(collectionList)){
            for (CustomizedOrderCollection collection : collectionList) {
                //收款记录改为未打印
                collection.setIsPrint(0);
                collection.setModifiedId(req.getUserId());
                int update = orderCollectionMapper.updateById(collection);
                if (update <= 0){
                    throw new BusinessException(SystemError.SYS_408);
                }

                collectionIdList.add(collection.getId());
                payMethodList.add(collection.getCollectionWay());
                payerList.add(collection.getPayer());
                //游客统计
                QueryWrapper<CustomizedOrderTouristInfo> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.lambda().eq(CustomizedOrderTouristInfo::getOrderId, req.getOrderId());
                queryWrapper2.lambda().eq(CustomizedOrderTouristInfo::getId, collection.getTouristId());
                queryWrapper2.lambda().eq(CustomizedOrderTouristInfo::getIsDeleted, 0);
                CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectOne(queryWrapper2);
                //旅客收据详情
                TouristReceiptInfoDTO touristReceiptInfoDTO = new TouristReceiptInfoDTO();
                touristReceiptInfoDTO.setTouristId(touristInfo.getId());
                touristReceiptInfoDTO.setReceiptAmount(touristInfo.getTotalPaidIn());
                touristReceiptInfoList.add(touristReceiptInfoDTO);

                totalCollectionAmount = totalCollectionAmount.add(collection.getPaidInAmount());
            }
        }
        //计算印花税
        if (isTax && totalCollectionAmount.compareTo(BigDecimal.ZERO) > 0){
            //计算印花税
            stampDutyAmount = totalCollectionAmount.multiply(new BigDecimal(Constants.STAMP_DUTY_RATIO));
        }
        //批量作废收据
        QueryWrapper<CustomizedOrderReceipt> receiptWrapper = new QueryWrapper<>();
        receiptWrapper.eq("order_id",req.getOrderId());
        receiptWrapper.eq("receipt_type",1);
        receiptWrapper.eq("receipt_status",1);
        receiptWrapper.eq("is_deleted",0);
        List<CustomizedOrderReceipt> receiptList = orderReceiptMapper.selectList(receiptWrapper);
        if (receiptList != null && receiptList.size() > 0){
            List<CustomizedOrderReceipt> list1 = new ArrayList<>();
            for (CustomizedOrderReceipt receipt : receiptList){
                //收据是否已开印花税
                CustomizedOrderReceiptDetails details = orderReceiptDetailsMapper.queryStampDutyReceipt(receipt.getId());
                if (details != null){
                    //已申请印花税 -> 删除数据 + 财务退印花税
                    //封装财务退印花税请求参数
                    StampTaxRefundAddReq addReq = packStampTaxRefundAddReq(order,receipt,now,req.getUserId(),details.getStampDutyAmount());
                    reqList.add(addReq);
                    //删除收据
                    int del = orderReceiptDetailsMapper.deleteById(details.getId());
                    if (del <= 0){
                        throw new BusinessException(SystemError.SYS_408);
                    }
                }
                receipt.setReceiptStatus(0);
                receipt.setVoidTime(LocalDateTime.now());
                receipt.setVoidReason(req.getVoidReason());
                receipt.setModifiedId(req.getUserId());
                list1.add(receipt);
            }
            boolean batch1 = updateBatchById(list1);
            if (!batch1){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //新增收据
        CustomizedOrderReceipt orderReceipt = new CustomizedOrderReceipt();
        orderReceipt.setId(SnowflakeIdWorker.nextId());
        orderReceipt.setOrderId(req.getOrderId());
        orderReceipt.setScheduleId(statistics.getScheduleId());
        orderReceipt.setReceiptHeader(receiptHeader);
        //生成收据单号
        String receiptNumber = numberService.getReceiptNumber(req.getUserId());
        if (StringUtils.isNotBlank(receiptNumber)){
            orderReceipt.setReceiptNumber(receiptNumber);
        }
        orderReceipt.setReceiptType(1);
        //订单收款统计
        AddReceiptTouristDTO addReceiptTouristDTO = orderCollectionMapper.queryAddDetailListByOrder(req.getOrderId(), Constants.INSURANCE_COLLECTION_ID,Constants.OTHER_COLLECTION_ID);
        if (addReceiptTouristDTO != null){
            //收据金额（保险、其他除外）
            orderReceipt.setReceiptAmount(addReceiptTouristDTO.getReceiptAmount());
            //包含旅客数量
            orderReceipt.setIncludeTouristNum(addReceiptTouristDTO.getPeopleNum().intValue());
        }
        orderReceipt.setCreateTime(LocalDateTime.now());
        orderReceipt.setReceiptStatus(0);
        orderReceipt.setCreateId(req.getUserId());
        orderReceipt.setIsDeleted(0);
        int insert = orderReceiptMapper.insert(orderReceipt);
        if (insert <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //批量作废销售收据
        orderReceiptDetailsMapper.delByOrder(req.getOrderId());
        //新增销售收据
        CustomizedOrderReceiptDetails receiptDetails = new CustomizedOrderReceiptDetails();
        receiptDetails.setId(SnowflakeIdWorker.nextId());
        receiptDetails.setOrderId(req.getOrderId());
        receiptDetails.setScheduleId(statistics.getScheduleId());
        receiptDetails.setReceiptId(orderReceipt.getId());
        receiptDetails.setReceiptType(1);
        receiptDetails.setTouristName(receiptHeader);
        receiptDetails.setCustomerRights(tripSchedule.getCustomerRights());
        //    receiptDetails.setCompanyNotes();
        receiptDetails.setReceiptStatus(1);
        TripScheduleAdvancedDTO advancedDTO = tripSchedule.getAdvancedDTO();
        if (advancedDTO != null){
            receiptDetails.setTeaPartyTime(advancedDTO.getTeaPartyTime());
            receiptDetails.setTeaPartyDate(advancedDTO.getTeaPartyDate());
        }
        if (isTax){
            receiptDetails.setStampDutyAmount(stampDutyAmount);
        }
        //销售收据json
        SalesReceiptJson salesReceiptJson = new SalesReceiptJson();
        salesReceiptJson.setPayMethod(payMethodList);
        salesReceiptJson.setPayer(payerList);
        salesReceiptJson.setTouristReceiptInfoList(touristReceiptInfoList);
        salesReceiptJson.setCollectionIdList(collectionIdList);
        salesReceiptJson.setTouristInfoDTOList(touristInfoDTOList);
        salesReceiptJson.setTourCode(tripSchedule.getTripNumber());
        salesReceiptJson.setDays(tripSchedule.getTravelDays());
        salesReceiptJson.setDepartureDate(tripSchedule.getDepartureDate().toLocalDate());
        salesReceiptJson.setDeliveryDate(tripSchedule.getDepartureDate().plusDays(tripSchedule.getTravelDays()).toLocalDate());
        salesReceiptJson.setDepDate(CharUtil.getWeekDay(tripSchedule.getDepartureDate().getDayOfWeek().getValue()));
        salesReceiptJson.setRoute(tripSchedule.getName());
        salesReceiptJson.setEnquiryNo(CharUtil.getRandomStr(6));
        salesReceiptJson.setEnquiryTimeTel(Constants.QUERY_TIME);
        salesReceiptJson.setReceiptNumber(numberService.getReceiptNumber(req.getUserId()));
        salesReceiptJson.setCollectionFee(statistics.getCollectionFee());
        salesReceiptJson.setAdjustmentCost(statistics.getAdjustmentCost());
        salesReceiptJson.setOtherAmount(statistics.getOtherAmount());
        salesReceiptJson.setGroupFee(statistics.getTotalTourFee());
        salesReceiptJson.setTotalReceivables(statistics.getTotalReceivables());
        salesReceiptJson.setPaidAmount(statistics.getTotalPaidIn());
        salesReceiptJson.setPayAmount(statistics.getTotalPaidIn());
        salesReceiptJson.setRemainingAmount(statistics.getRemainingReceivables());
        //定制包团须知
        salesReceiptJson.setTourFeeInclude(tripSchedule.getTourFeeInclude());
        salesReceiptJson.setTourFeeExclude(tripSchedule.getTourFeeExclude());
        salesReceiptJson.setSignNotice(tripSchedule.getSignNotice());
        salesReceiptJson.setRemark(tripSchedule.getRemark());
        receiptDetails.setReceipJson(JSON.toJSONString(salesReceiptJson));
        //收据关联旅客
        List<ReceiptTouristDTO> touristIdList = orderCollectionMapper.queryTouristIdByOrder(req.getOrderId(), Constants.INSURANCE_COLLECTION_ID,Constants.OTHER_COLLECTION_ID);
        if (touristIdList != null && touristIdList.size() > 0){
            List<CustomizedOrderReceiptTourist> orderReceiptTouristList = new ArrayList<>();
            for (ReceiptTouristDTO receiptTouristDTO : touristIdList){
                CustomizedOrderReceiptTourist orderReceiptTourist = new CustomizedOrderReceiptTourist();
                orderReceiptTourist.setId(SnowflakeIdWorker.nextId());
                orderReceiptTourist.setReceiptId(orderReceipt.getId());
                orderReceiptTourist.setOrderId(req.getOrderId());
                orderReceiptTourist.setTouristId(receiptTouristDTO.getTouristId());
                orderReceiptTourist.setReceiptAmount(receiptTouristDTO.getPaidInAmount());
                orderReceiptTourist.setCreateId(req.getUserId());
                orderReceiptTourist.setIsDeleted(0);
                orderReceiptTouristList.add(orderReceiptTourist);
            }
            Integer batch = orderReceiptTouristMapper.insertBatchSomeColumn(orderReceiptTouristList);
            if (batch < orderReceiptTouristList.size()){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //更新订单统计
        statistics.setReceiptedAmount(orderReceipt.getReceiptAmount());
        int updateStatistics = orderAmountStatisticsMapper.updateById(statistics);
        if (updateStatistics <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //更新订单收款（非保险）记录（插入receiptId）
   //     orderCollectionMapper.batchUpdateReceipt(req.getOrderId(),orderReceipt.getId(),req.getUserId(), CollectionTypeIdCode.INSURANCE.getCode());
        //新增销售收据
        int insertDetail = orderReceiptDetailsMapper.insert(receiptDetails);
        if (insertDetail <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //请求财务退印花税接口
        if (reqList.size() > 0){
            Result result = financeStampTaxRefundService.add(reqList, req.getUserId());
            if (result == null || result.getCode() != 0){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        return Result.success(orderReceipt.getId());
    }

    /**
     * 打印
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result printReceipt(CustomOrderReceiptDetailsRePrintReq req) {
        //销售收据
        CustomizedOrderReceiptDetails details = orderReceiptDetailsMapper.selectById(req.getId());
        if (details == null || Objects.equals(details.getReceiptStatus(),0)) {
            throw new BusinessException(SystemError.CUSTOM_ORDER_4024);
        }
        //收据
        CustomizedOrderReceipt receipt = getById(details.getReceiptId());
        if (receipt == null || Objects.equals(receipt.getIsDeleted(),1)) {
            throw new BusinessException(SystemError.CUSTOM_ORDER_4024);
        }
        if (Objects.equals(details.getIsPrint(),1)){
            return Result.success();
        }
        //更新销售收据
        details.setReceiptStatus(1);
        details.setIsPrint(1);
        details.setTouristName(req.getTouristName());
        details.setCompanyNotes(req.getCompanyNotes());
        details.setCustomerRights(req.getCustomerRights());
        details.setTeaPartyDate(req.getTeaPartyDate());
        //更新收据
        receipt.setReceiptHeader(req.getTouristName());
        receipt.setReceiptStatus(1);
        receipt.setModifiedId(req.getUserId());
        //团期信息
        CustomizedTripScheduleDTO tripSchedule = tripScheduleService.queryByScheduleId(receipt.getScheduleId());
        if (tripSchedule == null){
            throw new BusinessException(SystemError.CUSTOM_3006);
        }
        SalesReceiptJson salesReceiptJson = JSON.parseObject(details.getReceipJson(),SalesReceiptJson.class);
        //印花税
        //印花税金额
        BigDecimal stampDutyAmount = details.getStampDutyAmount();
        if(Objects.equals(Constants.AREA_HK, tripSchedule.getDeparturePlaceId())
                && !Objects.equals(Constants.AREA_HK, tripSchedule.getDestinationId())) {
            LevyRequest levyRequest = new LevyRequest();
            levyRequest.setReceiptNumber(receipt.getReceiptNumber());
            levyRequest.setNameOfTravelerPayer(req.getTouristName());
            levyRequest.setDepartureDate(DateUtil.fmtLocalDate(tripSchedule.getDepartureDate().toLocalDate(),"yyyy-MM-dd"));
            DecimalFormat nf = new DecimalFormat(StrConstant.DECIMAL_POINT4.getValue());
            levyRequest.setPremiumReceived(nf.format(stampDutyAmount));
            //付款人
            CustomizedOrderCollection collection = orderCollectionMapper.selectById(salesReceiptJson.getCollectionIdList().get(0));
            CustomizedOrderTouristInfo payer = orderTouristInfoMapper.selectById(collection.getPayerId());
            levyRequest.setLast4DigitOfContactPhoneNumber(payer.getMobile().substring(payer.getMobile().length() - 4));
            levyRequest.setBusinessType(SystemBusinessType.OUTBOUND_CUSTOMIZATION.getCode());
            levyRequest.setUserId(req.getUserId());
            Result<LevyDTO> levyDTOResult = levyService.levyEFrank(levyRequest);
            if (!levyDTOResult.isSuccess() || levyDTOResult.getData() == null) {
                throw new BusinessException(SystemError.SYS_500);
            }
            LevyDTO levyDTO = levyDTOResult.getData();
            details.setStampDutyPic(Base64.getEncoder().encodeToString(levyDTO.getLevystamp()));
            details.setStampDutyAmount(stampDutyAmount);
        }
        int updateDetail = orderReceiptDetailsMapper.updateById(details);
        boolean bl = updateById(receipt);
        if (updateDetail <= 0 || !bl){
            throw new BusinessException(SystemError.SYS_437);
        }
        //数据总金额
        BigDecimal totalReceiptAmount = BigDecimal.ZERO;
        //批量新增收据关联旅客
        List<TouristReceiptInfoDTO> touristReceiptInfoList = salesReceiptJson.getTouristReceiptInfoList();
        if (CollectionUtils.isNotEmpty(touristReceiptInfoList)){
            List<CustomizedOrderReceiptTourist> receiptTouristList = new ArrayList<>();
            for (TouristReceiptInfoDTO touristReceiptInfoDTO : touristReceiptInfoList){
                totalReceiptAmount = totalReceiptAmount.add(touristReceiptInfoDTO.getReceiptAmount());
                //收据关联旅客
                CustomizedOrderReceiptTourist receiptTourist = new CustomizedOrderReceiptTourist();
                receiptTourist.setId(SnowflakeIdWorker.nextId());
                receiptTourist.setReceiptId(receipt.getId());
                receiptTourist.setOrderId(receipt.getOrderId());
                receiptTourist.setTouristId(touristReceiptInfoDTO.getTouristId());
                receiptTourist.setReceiptAmount(touristReceiptInfoDTO.getReceiptAmount());
                receiptTourist.setCreateId(req.getId());
                receiptTourist.setGmtCreate(LocalDateTime.now());
                receiptTourist.setIsDeleted(0);
                receiptTouristList.add(receiptTourist);
                //更新旅客统计
                CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(touristReceiptInfoDTO.getTouristId());
                touristInfo.setReceiptedAmount(touristInfo.getReceiptedAmount().add(touristReceiptInfoDTO.getReceiptAmount()));
                touristInfo.setModifiedId(req.getUserId());
                int update = orderTouristInfoMapper.updateById(touristInfo);
                if (update <= 0){
                    throw new BusinessException(SystemError.SYS_437);
                }
            }
            if (receiptTouristList.size() > 0){
                //批量新增收据关联旅客
                Integer batch = orderReceiptTouristMapper.insertBatchSomeColumn(receiptTouristList);
                if (batch < receiptTouristList.size()){
                    throw new BusinessException(SystemError.SYS_437);
                }
            }
        }
        //订单统计
        QueryWrapper<CustomizedOrderAmountStatistics> statisticsQueryWrapper = new QueryWrapper<>();
        statisticsQueryWrapper.eq("order_id",details.getOrderId());
        CustomizedOrderAmountStatistics statistics = orderAmountStatisticsMapper.selectOne(statisticsQueryWrapper);
        statistics.setReceiptedAmount(statistics.getReceiptedAmount().add(totalReceiptAmount));
        int update = orderAmountStatisticsMapper.updateById(statistics);
        if (update <= 0) {
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(receipt.getId());
    }

    /**
     * 批量打印
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result printBatch(CustomOrderReceiptPrintBatchReq req) {
        //旅客列表
        List<CustomizedOrderTouristInfo> touristInfoList = orderTouristInfoMapper.selectBatchIds(req.getIdList());
        if (CollectionUtils.isEmpty(touristInfoList)){
            throw new BusinessException(SystemError.FINANCE_ERROR_17031);
        }

        //数据抬头
        String receiptHeader = "";
        CustomizedOrderTouristInfo firstTourist = touristInfoList.get(0);
        if (StringUtils.isNotBlank(firstTourist.getCnFullname())){
            receiptHeader = firstTourist.getCnFullname();
        }else{
            receiptHeader = firstTourist.getEnFullname();
        }

        //订单收据
        CustomizedOrderReceipt receipt = new CustomizedOrderReceipt();
        long receiptId = SnowflakeIdWorker.nextId();
        receipt.setId(receiptId);
        receipt.setReceiptNumber(numberService.getReceiptNumber(req.getUserId()));
        receipt.setReceiptHeader(receiptHeader);
        receipt.setOrderId(req.getOrderId());
        receipt.setScheduleId(req.getScheduleId());
        receipt.setReceiptType(1);
        receipt.setReceiptStatus(1);
        LocalDateTime now = LocalDateTime.now();
        receipt.setCreateId(req.getUserId());
        receipt.setGmtCreate(now);
        receipt.setIsDeleted(0);
        //收据金额
        BigDecimal receiptAmount = BigDecimal.ZERO;
        //旅客收据详情列表
        List<TouristReceiptInfoDTO> touristReceiptInfoList = new ArrayList<>();
        //收款ID总列表
        List<Long> collectionId = new ArrayList<>();
        //旅客信息
        List<ReceiptTouristInfoDTO> touristInfoDTOList = new ArrayList<>();
        //支付方式
        List<String> payMethodList = new ArrayList<>();
        //付款方
        List<String> payerList = new ArrayList<>();
        //是否计算印花税
        boolean isTax = false;
        CustomizedTripScheduleDTO tripSchedule = tripScheduleService.queryByScheduleId(receipt.getScheduleId());
        if(Objects.equals(Constants.AREA_HK, tripSchedule.getDeparturePlaceId()) && !Objects.equals(Constants.AREA_HK, tripSchedule.getDestinationId())) {
            isTax = true;
        }
        //印花税金额
        BigDecimal totalStampDutyAmount = BigDecimal.ZERO;

        for (CustomizedOrderTouristInfo touristInfo : touristInfoList){
            if (Objects.equals(touristInfo.getIsDeleted(),1) || Objects.equals(touristInfo.getIsFullInfo(),0)){
                continue;
            }
            //旅客未打印收据的收款记录
            QueryWrapper<CustomizedOrderCollection> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("tourist_id",touristInfo.getId());
            queryWrapper.eq("order_id",touristInfo.getOrderId());
            queryWrapper.ne("is_print",1);
            queryWrapper.eq("is_deleted",0);
            List<CustomizedOrderCollection> collectionList = orderCollectionMapper.selectList(queryWrapper);
            if (CollectionUtils.isEmpty(collectionList)){
                continue;
            }
            //旅客收款总金额
            BigDecimal collectionAmount = BigDecimal.ZERO;
            for (CustomizedOrderCollection collection : collectionList){
                payMethodList.add(collection.getCollectionWay());
                payerList.add(collection.getPayer());
                collectionId.add(collection.getId());
                //换算成港币
                BigDecimal hkdAmount = iMainDataCurrencyService.getHkdAmount(collection.getCurrencyTypeId(), collection.getPaidInAmount());
                receiptAmount = receiptAmount.add(hkdAmount);
                collectionAmount = collectionAmount.add(hkdAmount);
            }
            if (collectionAmount.compareTo(BigDecimal.ZERO) > 0){
                //计算印花税
                if (isTax){
                    //是否收据计算过印花税（0 否，1 是）
                    if (Objects.equals(touristInfo.getIsReceiptCalculated(),1)){
                        totalStampDutyAmount = totalStampDutyAmount.add(collectionAmount.multiply(new BigDecimal(Constants.STAMP_DUTY_RATIO)));
                    }else{
                        totalStampDutyAmount = totalStampDutyAmount.add((collectionAmount.subtract(touristInfo.getCollectionFee())).multiply(new BigDecimal(Constants.STAMP_DUTY_RATIO)));
                    }
                }
                //收据旅客信息
                ReceiptTouristInfoDTO touristInfoDTO = EntityUtil.copy(touristInfo,ReceiptTouristInfoDTO.class);
                touristInfoDTOList.add(touristInfoDTO);

                TouristReceiptInfoDTO touristReceiptInfoDTO = new TouristReceiptInfoDTO();
                touristReceiptInfoDTO.setTouristId(touristInfo.getId());
                touristReceiptInfoDTO.setReceiptAmount(collectionAmount);
                touristReceiptInfoList.add(touristReceiptInfoDTO);
            }
        }
        //无符合打印的数据
        if (receiptAmount.compareTo(BigDecimal.ZERO) <= 0 || touristReceiptInfoList.size() == 0){
            throw new BusinessException(SystemError.FINANCE_ERROR_17031);
        }
        receipt.setReceiptAmount(receiptAmount);
        receipt.setIncludeTouristNum(touristReceiptInfoList.size());
        //新增收据
        boolean save = save(receipt);
        //新增销售收据
        CustomizedOrderReceiptDetails receiptDetails = new CustomizedOrderReceiptDetails();
        receiptDetails.setId(SnowflakeIdWorker.nextId());
        receiptDetails.setOrderId(req.getOrderId());
        receiptDetails.setReceiptId(receiptId);
        receiptDetails.setReceiptType(1);
        receiptDetails.setReceiptStatus(1);
        receiptDetails.setTouristName(receiptHeader);
        receiptDetails.setCustomerRights(tripSchedule.getCustomerRights());
        //团期高级设置
        TripScheduleAdvancedDTO advancedDTO = tripSchedule.getAdvancedDTO();
        if (advancedDTO != null){
            receiptDetails.setTeaPartyDate(advancedDTO.getTeaPartyDate());
            receiptDetails.setTeaPartyTime(advancedDTO.getTeaPartyTime());
        }
        if (isTax && totalStampDutyAmount.compareTo(BigDecimal.ZERO) > 0){
            receiptDetails.setStampDutyAmount(totalStampDutyAmount);
        }
        //销售收据json
        SalesReceiptJson salesReceiptJson = new SalesReceiptJson();
        salesReceiptJson.setPayMethod(payMethodList);
        salesReceiptJson.setPayer(payerList);
        salesReceiptJson.setTouristReceiptInfoList(touristReceiptInfoList);
        salesReceiptJson.setCollectionIdList(collectionId);
        salesReceiptJson.setTouristInfoDTOList(touristInfoDTOList);
        salesReceiptJson.setTourCode(tripSchedule.getTripNumber());
        salesReceiptJson.setDays(tripSchedule.getTravelDays());
        salesReceiptJson.setDepartureDate(tripSchedule.getDepartureDate().toLocalDate());
        salesReceiptJson.setDeliveryDate(tripSchedule.getDepartureDate().toLocalDate().plusDays(tripSchedule.getTravelDays()));
        salesReceiptJson.setDepDate(CharUtil.getWeekDay(tripSchedule.getDepartureDate().getDayOfWeek().getValue()));
        salesReceiptJson.setRoute(tripSchedule.getName());
        salesReceiptJson.setEnquiryNo(OrderUtil.getRandom6());
        salesReceiptJson.setEnquiryTimeTel(Constants.QUERY_TIME);
        salesReceiptJson.setReceiptNumber(receipt.getReceiptNumber());
        //订单统计
        QueryWrapper<CustomizedOrderAmountStatistics> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomizedOrderAmountStatistics::getOrderId, req.getOrderId());
        CustomizedOrderAmountStatistics statistics = orderAmountStatisticsMapper.selectOne(queryWrapper);
        if (statistics == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
        }
        salesReceiptJson.setCollectionFee(statistics.getCollectionFee());
        salesReceiptJson.setAdjustmentCost(statistics.getAdjustmentCost());
        salesReceiptJson.setOtherAmount(statistics.getOtherAmount());
        salesReceiptJson.setGroupFee(statistics.getTotalTourFee());
        salesReceiptJson.setTotalReceivables(statistics.getTotalReceivables());
        salesReceiptJson.setPaidAmount(statistics.getTotalPaidIn());
        salesReceiptJson.setPayAmount(receiptAmount);
        salesReceiptJson.setRemainingAmount(statistics.getRemainingReceivables());
        //定制包团须知
        salesReceiptJson.setTourFeeInclude(tripSchedule.getTourFeeInclude());
        salesReceiptJson.setTourFeeExclude(tripSchedule.getTourFeeExclude());
        salesReceiptJson.setSignNotice(tripSchedule.getSignNotice());
        salesReceiptJson.setRemark(tripSchedule.getRemark());
        receiptDetails.setReceipJson(JSON.toJSONString(salesReceiptJson));
        int insert = orderReceiptDetailsMapper.insert(receiptDetails);
        if (!save || insert <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(receipt.getId());
    }

    /**
     * 取消
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result cancel(Long id, Long userId) {
        CustomizedOrderReceiptDetails details = orderReceiptDetailsMapper.selectById(id);
        if (details == null){
            throw new BusinessException(SystemError.SYS_411);
        }
        if (Objects.equals(details.getIsPrint(),1)){
            return Result.success();
        }
        int delete = orderReceiptDetailsMapper.deleteById(id);
        CustomizedOrderReceipt receipt = new CustomizedOrderReceipt();
        receipt.setId(details.getReceiptId());
        receipt.setModifiedId(userId);
        receipt.setIsDeleted(1);
        int update = orderReceiptMapper.updateById(receipt);
        if (delete <= 0 || update <= 0){
            throw new BusinessException(SystemError.SYS_408);
        }
        return Result.success();
    }

}
